//
//  FourthViewControllerOfFamous.m
//  FloatClouds
//
//  Created by 黄威 on 16/8/30.
//  Copyright © 2016年 黄威. All rights reserved.
//

#import "FourthViewControllerOfFamous.h"
#import "HWLNetworkTool.h"
#import "VIewPoint0.h"
#import "ViewPoint_Hot_Viewpoints.h"
#import "UIImageView+WebCache.h"
#import "ViewPointView.h"
#import "TAMacro.h"
#import "BaseButton.h"
#import "MJRefresh.h"
#import "ViewPointTableviewController.h"
#import "SVProgressHUD.h"

@interface FourthViewControllerOfFamous ()
@property (nonatomic, retain) UIScrollView *viewOfHeader;
@property (nonatomic, retain) NSMutableArray *arrayOfButton;
@property (nonatomic, retain) VIewPoint0 *viewPointModel;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, assign) NSInteger sn;
@property (nonatomic, assign) NSInteger btnTag;
@property (nonatomic, assign) NSInteger btnTag2;
@property (nonatomic, strong) NSMutableArray <ViewPoint_Hot_Viewpoints *>*arrayOfRefreshData;

@property (nonatomic, assign) NSInteger flag;
@end

@implementation FourthViewControllerOfFamous

- (void)viewDidLoad {
    self.arrayOfRefreshData = [NSMutableArray array];
    self.flag = 0;
    [super viewDidLoad];
    [self createHeaderView];
  
    [self.tableView registerClass:[ViewPointView class] forCellReuseIdentifier:@"ViewPointViewCell"];
        [self handleData];
         self.type = 0;
         self.sn = 0;
    self.btnTag2 = 10000;
    
    __weak typeof(self) weakSelf = self;
    //默认block方法：设置下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf refreshData2];
    }];
    
    //默认block方法：设置上拉加载更多
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //Call this Block When enter the refresh status automatically
        [weakSelf refreshDataSn];
    }];
    
    
}
-(void)refreshDataSn{
    
        if (self.btnTag2 == self.btnTag) {
            
        self.flag = 1; /************/
        self.sn = self.sn +10;
        [self refreshData2];
    }else {
       
        self.btnTag2 = self.btnTag;
        [self refreshData2];
         self.flag = 0;
        self.sn = 0;
        
    }
    
}



- (void)refreshData2{
    
   
    [SVProgressHUD show];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // time-consuming task
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            [SVProgressHUD showWithStatus:@"加载中..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD setMinimumDismissTimeInterval:5];
            
            
            
        });
    });
    
    NSString *sn = [NSString stringWithFormat:@"%ld",self.sn];
    NSString *type = [NSString stringWithFormat: @"%ld", self.type];
    NSString *dicOfBody = [[[@"sn="stringByAppendingString:sn]stringByAppendingString:@"&type="]stringByAppendingString:type];
    
    NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    [HWLNetworkTool POST:@"http://app.yanyue.cn/index/view" andBody:dicOfBody andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
        
      
        self.arrayOfRefreshData = self.viewPointModel.hot_viewpoints.mutableCopy;
        
        self.viewPointModel = [VIewPoint0 modelWithDic:result];
        
        [self.arrayOfRefreshData addObjectsFromArray:self.viewPointModel.hot_viewpoints];

        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        
    } andFailureBlock:^(NSError *error) {
        
    }];
    
    
}
- (void)handleData{
  
       NSString *dicOfBody = @"sn=0&type=0";
    NSDictionary *dicOfHeader = @{@"Content-Type":@"application/x-www-form-urlencoded"};
    
    [HWLNetworkTool POST:@"http://app.yanyue.cn/index/view" andBody:dicOfBody andBodyStyle:HWLBodyString andHeader:dicOfHeader andResponse:HWLJSON andSuccessBlock:^(id result) {
        
     self.viewPointModel = [VIewPoint0 modelWithDic:result];
        
        [self.tableView reloadData];
      
    } andFailureBlock:^(NSError *error) {
        
    }];
    
}
- (void)createHeaderView{
    
    self.arrayOfButton = [NSMutableArray array];
    self.viewOfHeader = [[UIScrollView alloc]init];
    self.viewOfHeader.frame = CGRectMake(0, 0,SCREEN_SIZE_WIDTH_ME *1 , 35);
    self.viewOfHeader.contentSize = CGSizeMake(SCREEN_SIZE_WIDTH_ME * 1.7, 35);
    self.viewOfHeader.showsHorizontalScrollIndicator = NO;
 
    NSUserDefaults *nightIsOn = [NSUserDefaults standardUserDefaults];
    NSString *isOn = [nightIsOn objectForKey:@"night"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(ON)
                                                 name:@"NIGHTON"
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(OFF)
                                                 name:@"NIGHTOFF"
                                               object:nil];
    
    
    if ([isOn isEqualToString:@"0"]) {
        
        self.viewOfHeader.backgroundColor = [UIColor whiteColor];
        
        
        
    }else if([isOn isEqualToString:@"1"]){
        
        self.viewOfHeader.backgroundColor = [UIColor colorWithRed:93/255.0 green:92/255.0 blue:101/255.0 alpha:1];
        
    }
    
    NSArray *arrayOfRankTitle = @[@"热点资讯",@"传统烟草",@"知识百科",@"感悟人生",@"浮云快报",@"相关周边"];
    
    for (int i = 10000; i < 10006; i++) {
        
        BaseButton *button = [BaseButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(SCREEN_SIZE_WIDTH_ME * 0.3 * (i - 10000), 0, (SCREEN_SIZE_WIDTH_ME  * 0.3), 30);
        button.tag = i;
        [self.viewOfHeader addSubview:button];
        [self.arrayOfButton addObject:button];
        
        [button setTitle:arrayOfRankTitle[i - 10000] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonOfData:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
    BaseButton *button = [self.viewOfHeader viewWithTag:10000];
    [button setTitleColor:[UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1] forState:UIControlStateNormal];
    
    
}




- (void)buttonOfData:(BaseButton *)button{
    
    for (BaseButton *btn in _arrayOfButton){
        if (btn.tag ==button.tag) {
            [btn setTitleColor:[UIColor colorWithRed:18.0 / 255 green:86.0 / 255 blue:138.0 / 255 alpha:1] forState:UIControlStateNormal];
        } else {
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        }
    }
    
    switch (button.tag) {
        case 10000:
        {   self.btnTag = 10000;
            self.type = 0;
            self.sn = 0;
            [self refreshData2];
       break;
        }
        case 10001:
        {
            self.type = 1;
            self.btnTag = 10001;
             self.sn = 0;
            [self refreshData2];
        }
            break;
            
        case 10002:{
            self.type = 2;
            self.btnTag = 100002;
             self.sn = 0;
            [self refreshData2];
                }
         break;
            
        case 10003:{
            self.type = 3;
            self.btnTag = 10003;
             self.sn = 0;
           [self refreshData2];
        }
            break;
            
        case 10004:{
             self.type = 4;
            self.btnTag = 10004;
             self.sn = 0;
            [self refreshData2];
        }
            break;
            
        case 10005:{
            self.type = 5;
            self.btnTag = 100005;
             self.sn = 0;
            [self refreshData2];
        }
            break;
        default:
            
            break;
    } 
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (self.flag == 1) {
        
        
        return self.arrayOfRefreshData.count;
        
        
    }
    
    
    return self.viewPointModel.hot_viewpoints.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        return self.viewOfHeader;
        
    }
    
    
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return 35;
    
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    if (self.flag == 1) {
      
        ViewPoint_Hot_Viewpoints *hots = self.arrayOfRefreshData[indexPath.row];
        
        ViewPointView *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ViewPointViewCell"];
        cell.title.text = hots.title;
        NSURL *url = [NSURL URLWithString:hots.photo];
        [cell.imageViewRight sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
        cell.content.text = hots.content;
        
        
        return cell;
        
    }
    
    
        ViewPointView *cell = [self.tableView dequeueReusableCellWithIdentifier:@"ViewPointViewCell"];
       cell.title.text = self.viewPointModel.hot_viewpoints[indexPath.row].title;
       NSURL *url = [NSURL URLWithString:self.viewPointModel.hot_viewpoints[indexPath.row].photo];
       [cell.imageViewRight sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"]];
       cell.content.text = self.viewPointModel.hot_viewpoints[indexPath.row].content;
       return cell;
  
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    return 95;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


    if (self.flag == 1) {
        
        
        NSString *picid = self.arrayOfRefreshData[indexPath.row].uid;
        ViewPointTableviewController *point = [[ViewPointTableviewController alloc]init];
        point.viewId = picid;
        [self.navigationController pushViewController:point animated:YES];

        
    }


    if (self.flag == 0) {
        NSString *picid = self.viewPointModel.hot_viewpoints[indexPath.row].uid;
        ViewPointTableviewController *point = [[ViewPointTableviewController alloc]init];
        point.viewId = picid;
        

    [self.navigationController pushViewController:point animated:YES];
 
       
       
    }



}



// 去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 35;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (void)ON{
    
    self.viewOfHeader.backgroundColor =  [UIColor colorWithRed:93/255.0 green:92/255.0 blue:101/255.0 alpha:1];
    
    
}

- (void)OFF{
    //lanse
    self.viewOfHeader.backgroundColor =[UIColor whiteColor];
    
    
}
- (void)dealloc{
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHTON" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"NIGHTOFF"object:nil];
    
    
}

@end
